//
//  UserAccount.m
//  School+
//
//  Created by Sean Sebastian on 16/5/1.
//  Copyright © 2016年 Sean Sebastian. All rights reserved.
//

#import "UserAccount.h"

#import "NSString+BYDateAndString.h"

@interface UserAccount ()

// 用户数据路径
@property (nonatomic , copy) NSString *accountPath;

@end

@implementation UserAccount

SingletonCreate_m(UserAccount);

- (void)setUsername:(NSString *)username
{
    _username = username;
}

- (void)saveUserInfo
{
    [NSKeyedArchiver archiveRootObject:self toFile:self.accountPath];
}

- (void)loadUserInfo
{
    [NSKeyedUnarchiver unarchiveObjectWithFile:self.accountPath];
}

- (void)deleteUserInfo
{
    [NSKeyedUnarchiver unarchiveObjectWithFile:self.accountPath];
    /*
     @property (nonatomic , copy) NSString *username;
     @property (nonatomic , copy) NSString *password;
     @property (nonatomic , copy) NSString *email;
     @property (nonatomic , copy) NSString *iconImageURL;
     @property (nonatomic , strong) NSDate *createTime;
     @property (nonatomic  ,assign) int userID;
     */
    
    self.username = nil;
    self.password = nil;
    self.email = nil;
    self.userID = 0 ;
    self.createTime = nil;
    
    
    
    [self saveUserInfo];
    NSLog(@"%@" , self);
}

/**
 归档 -- encoder
 将自定义的对象写入磁盘前，将对象转成“二进制”
 */
- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:_username forKey:@"username"];
    [encoder encodeObject:_password forKey:@"password"];
    [encoder encodeObject:_email forKey:@"email"];
    [encoder encodeObject:_iconImageURL forKey:@"iconImageURL"];
    [encoder encodeObject:_createTime forKey:@"createTime"];
    [encoder encodeInt:_userID forKey:@"userID"];
}

/**
 解档 --- decoder
 将磁盘上保存的二进制数据，转成自定义的对象
 */
- (instancetype)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
        _username = [decoder decodeObjectForKey:@"username"];
        _password = [decoder decodeObjectForKey:@"password"];
        _email = [decoder decodeObjectForKey:@"email"];
        _iconImageURL = [decoder decodeObjectForKey:@"iconImageURL"];
        _createTime = [decoder decodeObjectForKey:@"createTime"];
        _userID = [decoder decodeIntForKey:@"userID"];
    }
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"userID:%d,username:%@ , password:%@ , email:%@ , iconImageURL:%@ , createTime:%@" , self.userID,self.username , self.password,self.email , self.iconImageURL, [NSString stringFromDate:self.createTime ]];
}

- (NSString *)accountPath
{
    NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    return [NSString stringWithFormat:@"%@/Account.plist" , str];
}

- (BOOL)isSignIn
{
    if (self.username != nil) {
        return YES;
    }
    return NO;
}

@end
